package reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import reggie.common.R;
import reggie.entity.User;
import reggie.service.UserService;
import reggie.utils.ValidateCodeUtils;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * "验证码"发送
     *
     * @param phone
     * @param session
     * @return
     */
    @GetMapping("/sendMsg")
    public R<String> sendMag(String phone, HttpSession session) {
        String code = ValidateCodeUtils.generateValidateCode(4).toString();
        System.out.println("随机码为: " + code);
        session.setAttribute(phone, code);
        return R.success("发送成功");
    }


    /**
     * 用户登录
     *
     * @param map
     * @param session
     * @return
     */
    @PostMapping("/login")
    public R<String> login(@RequestBody Map<String, String> map, HttpSession session) {
        String code = (String) session.getAttribute(map.get("phone"));
        if (code != null && code.equals(map.get("code"))) {
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getPhone, map.get("phone"));
            User one = userService.getOne(queryWrapper);
            if (one == null) {
                return R.error("用户不存在");
            } else {
                session.setAttribute("user", one);
                session.removeAttribute(map.get("phone"));
                return R.success("");
            }
        } else {
            return R.error("验证码错误");
        }
    }

    /**
     * 用户退出
     *
     * @param session
     * @return
     */
    @PostMapping("loginout")
    public R<String> loginOut(HttpSession session) {
        session.removeAttribute("user");
        return R.success("退出成功!");
    }
}
